from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings


import re
from celery_tasks.email.tasks import send_verify_email
from .models import User, Address
from goods.models import SKU


# 用户浏览记录的序列化器
class AddUserBrowseHistory(serializers.Serializer):
    # 接收参数
    sku_id = serializers.IntegerField(label='商品SKU编号', min_value=1)
    # 校验参数
    def validate_sku_id(self, value):
        # 确认商品存在未下架
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id 不存在')

        return value

    def create(self, validated_data):
        """
        获取连接到redis对象， 去重， 新增， 截取
        :param validated_data:
        :return:
        """
        # 获取登录用户的user_id
        user_id = self.context['request'].user.id
        # 获取sku_id
        sku_id = validated_data['sku_id']

        redis_conn = get_redis_connection('history')
        # 使用管道， 优化redis访问效率
        pl = redis_conn.pipeline()
        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 新增
        pl.lpush('history_%s' % user_id, sku_id)
        # 截取
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行
        pl.execute()
        return validated_data


# 更新邮箱的序列化器
class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        instance.email = validated_data['email']
        instance.save()
        # instance就是前面的User对象
        # 在保存之后，返回之前需要生成邮箱的激活链接
        verify_url = instance.generate_verify_email_url()

        # 异步发送邮件
        send_verify_email.delay(instance.email, verify_url)

        return instance


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详情信息的序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


# 绑定用户的序列化器
class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)

    # 补充token字段， 用于输出
    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 检测手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3456789]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    # 检测是否同意协议
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意协议')
        return value

    # 判断验证码及密码
    def validate(self, data):
        # 判断两次密码是否一致
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        if real_sms_code is None:
            raise serializers.ValidationError('验证码无效')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        """创建用户"""
        # 先删除无用的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        # 调用django认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 在响应数据之前写入JWT_token

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 将token与user绑定在一起响应出去
        user.token = token

        return user


# 用户地址的序列化器
class UserADDressSerializer(serializers.ModelSerializer):
    # 定义输出字段
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    # 指定输出的字段
    class Meta:
        model = Address
        # 除了以下字段都输出
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    # 校验手机号
    def validate_mobile(self, value):
        if not re.match(r'^1[3456789]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    # 保存
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """地址标题序列化器"""
    class Meta:
        model = Address
        fields = ('title')


class ChangePasswordSerializer(serializers.ModelSerializer):
    """
    修改密码序列化器
    """
    password2 = serializers.CharField(label='确认密码', write_only=True)
    old_password = serializers.CharField(label='原密码', write_only=True)

    class Meta:
        model = User
        fields = ('id', 'password', 'password2', 'old_password')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate(self, data):
        """
        校验数据
        """
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断原密码是否正确
        if not self.instance.check_password(data['old_password']):
            raise serializers.ValidationError('原密码错误')

        return data

    def update(self, instance, validated_data):
        """
        更新密码
        """
        # 调用django 用户模型类的设置密码方法
        instance.set_password(validated_data['password'])
        instance.save()
        return instance






















